import { ICmdDialogParams } from '@amcax/base';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import GeomSetWidget from '@app-cad/common/RJSFWidgets/GeomSetWidget';
import { CurvedBaseCommand } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useState } from 'react';

type FormDataType = {
  name?: string;
  parent?: string;
};

function GeomSetDialog({ title, onClose }: ICmdDialogParams) {
  const [formData, setFormData] = useState<FormDataType>({});
  const [isLoading, setIsLoading] = useState(false);

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      name: { type: 'string', title: '名称' },
      parent: { type: 'string' },
    },
  };

  const finishDraw = async () => {
    setIsLoading(true);
    try {
      await confirmCommand({
        c: 'CreateGeomSet',
        name: formData.name,
        parent: formData.parent,
      });
    } finally {
      setIsLoading(false);
    }
    onClose();
  };

  const { confirmCommand } = useCommand('geomSet', {
    commandName: 'CreateGeomSet',
    onClose,
    finishDraw,
  });

  return (
    <PickableCommandForm
      onClose={onClose}
      title={title}
      schema={schema}
      widgets={{
        geomSet: GeomSetWidget,
      }}
      formData={formData}
      submitLoading={isLoading}
      onChange={(v) => setFormData(v)}
      extraUiSchema={{
        name: {
          'ui:placeholder': '请输入名称',
          'ui:autofocus': true,
          'ui:autocomplete': 'off',
        },
        parent: {
          'ui:options': {
            placeholder: '请选择父级几何图形集（可选）',
          },
          'ui:widget': 'geomSet',
          'ui:label': false,
        },
      }}
      submitText='完成'
      onSubmit={finishDraw}
    />
  );
}

export const cmdGeomSet: CurvedBaseCommand = {
  id: 'CreateGeomSet',
  label: '创建几何图形集',
  icon: 'commands/curved/geomSet',
  create: (label, onClose) => (
    <GeomSetDialog
      title={label}
      onClose={onClose}
    />
  ),
};
